<script setup>
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useAdminStore } from '@/stores/admin'
import * as echarts from 'echarts'

const adminStore = useAdminStore()
const loading = ref(false)
const chartRef = ref(null)
const chartInstance = ref(null)

const courseStatistics = ref([
  { category: '前端', totalCourses: 12 },
  { category: '后端', totalCourses: 8 },
  { category: 'AI', totalCourses: 5 }
])

const courseWatchCount = ref([
  { chapter: 'Vue3入门', views: 120 },
  { chapter: 'Node实战', views: 80 }
])

const fetchStatistics = async () => {
  try {
    loading.value = true
    const response = await adminStore.getStatistics()
    courseStatistics.value = response.courseStatistics
    courseWatchCount.value = response.courseWatchCount
  } catch (error) {
    console.error('Failed to fetch statistics:', error)
    ElMessage({
      message: '获取统计数据失败，已显示模拟数据',
      type: 'warning',
      duration: 5 * 1000
    })
  } finally {
    loading.value = false
  }
}

const updateChart = () => {
  if (!chartRef.value) return
  if (!chartInstance.value) {
    chartInstance.value = echarts.init(chartRef.value)
  }
  const option = {
    title: { text: '课程类型分布', left: 'center' },
    tooltip: { trigger: 'item' },
    legend: { bottom: 0 },
    series: [
      {
        name: '课程数',
        type: 'pie',
        radius: '60%',
        data: courseStatistics.value.map(item => ({
          value: item.totalCourses,
          name: item.category
        }))
      }
    ]
  }
  chartInstance.value.setOption(option)
}

// 定义 handleResize 函数，以便在 onUnmounted 中正确移除监听器
const handleResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize()
  }
}

onMounted(() => {
  fetchStatistics()
  nextTick(() => {
    updateChart()
  })

  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (chartInstance.value) {
    chartInstance.value.dispose()
  }
})
</script>

<template>
  <div class="statistics">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span style="font-size: 20px; font-weight: bold; display: flex; align-items: center; white-space: nowrap; flex-grow: 1; flex-shrink: 0;" >
                课程类型分布
              </span>
            </div>
          </template>
          <div ref="chartRef" style="height: 400px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span style="font-size: 20px; font-weight: bold; display: flex; align-items: center; white-space: nowrap; flex-grow: 1; flex-shrink: 0;" >
                课程观看排行
              </span>
            </div>
          </template>
          <el-table :data="courseWatchCount" style="width: 100%" border>
            <el-table-column prop="chapter" label="章节名称" />
            <el-table-column prop="views" label="观看次数" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.statistics {
  padding: 0;
  width: 100%;
}

.el-card {
  width: 100% !important;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.04);
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  padding-bottom: 8px;
  flex-wrap: wrap;
}

.el-table th {
  background: #f5f7fa;
  color: #34495e;
  font-weight: bold;
}
</style> 